from datetime import datetime
import json

from src import db

class DictMixin:
    """Mixin类, 继承后可使用to_dict()方法将对象转为dict"""
    def to_dict(self):
        return self.__convert_dict(self.__dict__)
    
    def __convert_dict(self, attrs):
        result = {}
        for key, value in attrs.items():
            result[key] = self.__convert_value(value)
        
        return result
            
    def _convert_value(self, value):
        if isinstance(value, DictMixin):
            return self.to_dict()
        elif isinstance(value, dict):
            return self.__convert_dict(value)
        elif isinstance(value, list):
            return [self.__convert_value(v) for v in value]
        elif hasattr(value, "__dict__"):
            return self.__convert_dict(value.__dict__)
        else:
            return value
        
class JsonMixin:
    """Mixin类, 必须同时继承DictMixin类, 继承后可使用to_json()方法将对象转为json字符串"""
    def to_json(self):
        return json.dumps(self.to_dict()) 
        

class BaseModel(db.Model, DictMixin, JsonMixin):
    # 基类模型
    __abstract__ = True

    created = db.Column(db.DateTime, nullable=False, default=datetime.utcnow)  # 创建时间
    updated = db.Column(db.DateTime, nullable=False, default=datetime.utcnow, onupdate=datetime.utcnow)  # 更新时间
    
    
